package com.pjb.springbootjjwt.store.entity;

import com.pjb.springbootjjwt.store.Defines;
import com.pjb.springbootjjwt.store.utils.FileUtil;
import lombok.Data;
import org.apache.commons.lang3.StringUtils;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * 一行记录
 */
@Data
public class Line {

    /**
     * 主键
     */
    private String key;

    /**
     * 行号
     */
    private int no;

    /**
     * 行长度
     */
    private int length;
    private List<String> data = new ArrayList<>();

    /**
     * 将字符串记录转换为对象
     *
     * @param lineStr 0000            :0000                2b                  3c
     * @return
     */
    public static Line toLine(String lineStr, List<Integer> len) {
        if (StringUtils.isEmpty(lineStr) || lineStr.trim().isEmpty()) return null;

        String[] array = lineStr.split(":");
        Line line = new Line();
        line.setKey(array[0].trim());
        line.setData(FileUtil.reover(array[1], len));
        return line;
    }

    public static Line toLine(String lineStr) {
        Line line = new Line();
        line.setKey("vchar");

        List<String> list = new ArrayList<>();
        list.add(lineStr);
        line.setData(list);
        return line;
    }

    public static List<String> get(List<Line> from, int i) {
        List<String> list = new ArrayList<>();
        for (Line line : from) {
            if (i < line.getData().size())
                list.add(line.getData().get(i));
        }
        return list;
    }

    public static void main(String[] args) throws Exception {
        Line line = new Line();
        line.setKey("123");
        line.setData(Arrays.asList("a", "b", "c"));
        List<Integer> list = Arrays.asList(64, 64, 64);
        String lineStr = line.toText(list);
        System.out.println(lineStr);
        System.out.println(toLine(lineStr, list));
    }

    /**
     * 将对象转换为字符串记录
     *
     * @return
     */
    public String toText(List<Integer> len) {
        return FileUtil.overStr("" + this.getNo(), FileUtil.DEFAULT_SIZE) + ":" + FileUtil.overStr(this.data, len);
    }

    public String toIndex(String table) throws IOException {
        return FileUtil.overStr("" + this.getKey(), Defines.pkLength(table)) + ":" + FileUtil.overStr("" + this.getNo(), FileUtil.DEFAULT_SIZE);
    }
}
